package com.example.springlearn.interceptor;

import com.example.springlearn.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserMsgInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            response.sendRedirect("/");
            return false;
        }

        Cookie usernameCookie = CookieUtil.getCookieByKey(cookies, "username");
        Cookie uidCookie = CookieUtil.getCookieByKey(cookies, "uid");

        if (usernameCookie == null || uidCookie == null) {
            response.sendRedirect("/");
            return false;
        }

        String username = usernameCookie.getValue();
        String uid = uidCookie.getValue();

        if (username != null && uid != null) {
            return true;
        }

        response.sendRedirect("/");
        return false;

    }
}
